package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.PostDubbleEvent;
import com.jackrain.nea.common.QueryCpUtil;
import com.jackrain.nea.common.QueryUserUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewDLTranWeightInfoCmd;
import com.jackrain.nea.fc.dl.mapper.ViewDLTranWeightInfoMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.HashMap;


/**
 * 称重系统数据传输
 *
 * @author kangcong
 * @date 2018/08/07
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewDLTranWeightInfoCmdImpl extends CommandAdapter implements ViewDLTranWeightInfoCmd {

    @Autowired
    QueryCpUtil queryCpUtil;

    @Autowired
    private QueryUserUtil queryUserUtil;

    @Autowired
    PostDubbleEvent postDubbleEvent;

    private final String BILL_TYPE = "TRAN_BOX";

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
//        log.debug("------------ViewDLTranWeightInfoCmdImpl：" + map.toString());
        log.info("ViewDLTranWeightInfoCmdImpl--map-->{}",map);

        ValueHolder vh = new ValueHolder();
        ViewDLTranWeightInfoMapper viewDLTranWeightInfoMapper = ApplicationContextHandle.getBean(ViewDLTranWeightInfoMapper.class);
        JSONObject data = null;

        try {
            String param = map.get("param").toString();
            JSONObject param1 = JSON.parseObject(param);

            if (null == param1 || param1.size() == 0) {
                throw new NDSException("param is null!");
            }

            data = param1.getJSONObject("data");
            if (null == data || data.size() == 0) {
                throw new NDSException("data is null!");
            }
        } catch (Exception e) {
            vh.put("code", -1);
            vh.put("message", "本次数据插入失败,参数转换异常:" + map.toString());

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            if ((e instanceof NDSException)) {
                throw e;
            } else {
                throw new NDSException(sw.toString());
            }

        }
        if (vh.getData().size() > 0) {
            return vh;
        }

        String billline = null;
        String billno = null;
        String lineno = null;
        double weight = 0;
        String acceptstore = null;
        Long origid = null;
        Long destid = null;
        String province = null;

        try {
            billline = data.getString("BILL_LINE").trim();
            String[] arr = billline.split("_");
            billno = arr[0];
            lineno = arr[1];
            weight = TypeUtils.castToDouble(data.getString("WEIGHT").trim());

            if ("".equals(billno.trim()) || "".equals(lineno.trim())) {
                throw new NDSException("param is exception!" + map);
            }
            //根拔单号获取收发店仓id
            HashMap map3 = viewDLTranWeightInfoMapper.selectStoreIdByBillno(billno);

            if (map3.get("CP_C_ORIG_ID") == null || map3.get("CP_C_DEST_ID") == null) {
                throw new NDSException("CP_C_ORIG_ID or CP_C_DEST_ID  is null!");
            }

            origid = TypeUtils.castToLong(map3.get("CP_C_ORIG_ID"));
            destid = TypeUtils.castToLong(map3.get("CP_C_DEST_ID"));

            if (destid == null || origid == null) {
                throw new NDSException("CP_C_ORIG_ID or CP_C_DEST_ID  is null!");
            }

            //通过id获取收货店仓名字 省份id
            JSONObject whereJs1 = new JSONObject();
            whereJs1.put("ID", map3.get("CP_C_DEST_ID"));
            JSONObject h1 = queryCpUtil.queryCP("CP_C_STORE", "ENAME,CP_C_PRO_ID", whereJs1);
            acceptstore = h1.getString("ENAME");
            Long proid = h1.getLong("CP_C_PRO_ID");

            //通过id获取省份名
            JSONObject whereJs2 = new JSONObject();
            whereJs2.put("ID", proid);
            JSONObject h2 = queryCpUtil.queryCP("CP_C_REGION", "ENAME", whereJs2);
            province = h2.getString("ENAME");

        } catch (Exception e) {
            vh.put("code", -1);
            vh.put("message", "保存失败，参数异常：" + map);
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
        }
        if (vh.getData().size() > 0) {
            return vh;
        }

        try {
            //判断单据在数据库中的数量
            JSONObject insertKeys = new JSONObject();
            Long billid = viewDLTranWeightInfoMapper.selectTranBillId(billno);
            if (billid == null) {
                vh.put("code", -1);
                vh.put("message", "查询不到对应的单据，BILLNO为" + billno);
                return vh;
            }

            insertKeys.put("BILL_TYPE", BILL_TYPE);
            insertKeys.put("BILL_NO", billno);
            insertKeys.put("LINE_NO", lineno);
            insertKeys.put("BILL_LINE", billline);
            insertKeys.put("WEIGHT", weight);
            insertKeys.put("CREATETIME", new Timestamp(System.currentTimeMillis()).toString());
            insertKeys.put("BILL_ID", billid);
            insertKeys.put("OWNERID", 999999);
            insertKeys.put("OWNERENAME", "INTER99999");
            insertKeys.put("OWNERNAME", "INTER99999");
            insertKeys.put("CREATIONDATE", new Timestamp(System.currentTimeMillis()).toString());
            insertKeys.put("MODIFIERID", 999999);
            insertKeys.put("MODIFIERENAME", "INTER99999");
            insertKeys.put("MODIFIERNAME", "INTER99999");
            insertKeys.put("MODIFIEDDATE", new Timestamp(System.currentTimeMillis()).toString());
            insertKeys.put("ISACTIVE", "Y");
            insertKeys.put("CP_C_ORIG_ID", origid);
            insertKeys.put("CP_C_DEST_ID", destid);

            //调用修改标服
            String userName = "INTER99999";
            User user = queryUserUtil.getUser(userName);
            QuerySessionImpl querySession = new QuerySessionImpl(user);
            String noticSave = "com.jackrain.nea.dl.tran.api.BtranWeightSaveCmd:1.0:dl";

            JSONObject fixcolumn = new JSONObject();
            fixcolumn.put("DL_T_TRAN_WEIGHT_INFO", insertKeys.toJSONString());

            DefaultWebEvent event = new DefaultWebEvent("dltranweightinfo", new HashMap(16));
            event.put("param", fixcolumn);
            accesLogger.info("ViewDLTranWeightInfoCmdImpl--fixcolumn-->{}",fixcolumn);

//            log.debug("------------称重接口保存调用标服参数=" + fixcolumn);
            querySession.setEvent(event);

            JSONObject retSaveJo = postDubbleEvent.executePostDubble(noticSave, querySession);

            if (retSaveJo == null) {
                vh.put("code", -1);
                vh.put("message", "调用保存，调用标服返回为空");
                return vh;
            }
            accesLogger.info("ViewDLTranWeightInfoCmdImpl--retSaveJo-->{}",retSaveJo);
//            log.debug("retSaveJo" + retSaveJo);
            if (retSaveJo.containsKey("code") && (int) retSaveJo.get("code") != 0) {
                if (null == retSaveJo.get("message")) {
                    vh.put("code", -1);
                    vh.put("message", "调用失败，调用标服返回为空");
                    return vh;
                } else {
                    vh.put("code", -1);
                    vh.put("message", "调用失败，->" + retSaveJo.get("message"));
                    return vh;
                }
            }

            vh.put("code", 0);
            vh.put("message", "success");
            vh.put("storename", acceptstore);
            vh.put("province", province);

        } catch (Exception e) {
            vh.put("code", -1);
            vh.put("message", "调用保存失败" + e);

            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
        }
        return vh;
    }
}
